import Client from "./common";
import router from '../router';

import { store } from '../vuex/store';

const dataURLtoFile =(dataurl, filename) => {//将base64转换为文件
  let  arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
  bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while(n--){
        u8arr[n] = bstr.charCodeAt(n);
    }
  return new File([u8arr], filename, {type:mime});
}
const setToken = (token) => {
  let newTime = (new Date().getTime()); // 当前时间
  let expTime = 1000 * 60 * 60 * 24 * 30;
  let endTime = newTime + expTime;
  let tokenObj = {
    token: token,
    time: endTime
  };
  Client.setStore("feiyuToken", tokenObj);
  router.push({path: "/"});
}
const delToken = () => {
  Client.removeStore("feiyuToken");
  router.push({path: "/login"});
}

const toLogin = () => {
  router.push({path: "/login"});
};

const getImg = (str, index) => {
  if(str.indexOf(",")>0){
    let arr = str.split(',')
    return arr[index];
  }else {
    return str;
  }
}

const routeExpire =() => {
  router.beforeEach( (to, from, next) => {
    let obj,expireTime,currentTime,isExpire;
    obj = Client.getStore("feiyuToken");
    if(obj) {
      expireTime = obj.time;
      currentTime = (new Date()).getTime();
      isExpire = expireTime - currentTime;
      if(isExpire<=0){
        Client.removeStore("feiyuToken");
        next('/login');
      }else if(to.fullPath != "/login") {
        next();
      }else{
        next('/');
      }
    }else{
      if(to.fullPath != "/login"){
        next('/login');
      }else{
        next();
      }
    }
  })
}


const countCart = () => {
  let cartStore = Client.getSession("cart");
  let result = {
    money: 0,
    number: 0
  };
  if(cartStore && cartStore.length>0) {
    for(let i=0; i<cartStore.length; i++) {
      for(let j=0; j<cartStore[i].productList.length; j++) {
        result.money += (cartStore[i].productList[j].productPrice * cartStore[i].productList[j].number);
        result.number += cartStore[i].productList[j].number;
      }
    }
  }
  return result;
}

const clearCart = () => {
  Client.removeSession("cart");
}

const deleteCart = (productId) => {
  let cartStore = Client.getSession("cart");
  for(let i=0; i<cartStore.length; i++) {
    for(let j=0; j<cartStore[i].productList.length; j++) {
      
      if(cartStore[i].productList[j].productId == productId) {
        if(cartStore[i].productList.length>1) {
          cartStore[i].productList.splice(j, 1);
          store.commit('changeCart');
          break;
        }else {
          cartStore.splice(i, 1);
          store.commit('changeCart');
          break;
        }
      }
    }
  }
  Client.setSession("cart", cartStore)
}

const handleCart = (productId, type) => {
  let cartStore = Client.getSession("cart");
  for(let i=0; i<cartStore.length; i++) {
    for(let j=0; j<cartStore[i].productList.length; j++) {
      if(cartStore[i].productList[j].productId == productId ) {
        if(type == "remove" && cartStore[i].productList[j].number>1){
          store.commit('changeCart');
          cartStore[i].productList[j].number -= 1;
          break;
        }else if(type == "add") {
          
          store.commit('changeCart');
          cartStore[i].productList[j].number += 1;
          break;
        }
        
      }
    }
  }
  Client.setSession("cart", cartStore)
}

const addCart = (product) => {
  // 商品添加购物车之前，获取缓存里已选购的商品
  let cartStore = Client.getSession("cart");
  if(cartStore){
    let isExist = false;
    for(let i=0; i<cartStore.length; i++) {
      if(cartStore[i].shopId == product.shopId) {
        let isTrue = false;
        for(let j=0; j<cartStore[i].productList.length; j++) {
          if(cartStore[i].productList[j].productId == product.productId) {
            cartStore[i].productList[j].number += 1;
            isTrue = true;
            break;
          }
        }
        if(!isTrue) {
          product.number = 1;
          cartStore[i].productList.push(product);
        }
        isExist = true;
      }
    }
    if(!isExist) {
      product.number = 1;
      let obj = {
        shopId: product.shopId,
        shopName: product.shopName,
        productList:[product]
      }
      cartStore.push(obj);
    }
  }else {
    cartStore = [];
    product.number = 1;
    let obj2 = {
      shopId: product.shopId,
      productList:[product]
    }
    cartStore.push(obj2)
  }
  store.commit('changeCart');
  Client.setSession("cart", cartStore);
}

const Utils = {
  dataURLtoFile,
  routeExpire,
  toLogin,
  getImg,
  setToken,
  delToken,
  countCart,
  deleteCart,
  handleCart,
  addCart,
  clearCart
}
export default Utils